
import cv2 as cv
import time
import pymysql

id = 5
def insert_sql():
    # 建立连接
    conn = pymysql.connect(
        host="localhost",
        # host="192.168.1.112",
        user="root",  # 用户名
        passwd="newpassword",  # 用户密码
        db="检测小车")  # 数据库名

    global id
    # 创建游标，默认是元组型
    cursor = conn.cursor()
    # sql = "select * from t_plane"#数据库中表的名
    sql = '''INSERT INTO t_plane(id,x,y) VALUES(num,7,2);'''  # 数据库中表的名
    sql = sql.replace("num", str(id))
    cursor.execute(sql)
    conn.commit()
    id += 1
    cursor.close()
    conn.close()


# 加载训练数据集文件
recogizer=cv.face.LBPHFaceRecognizer_create()
recogizer.read('trainer/trainer1.yml')

# 加载特征数据
face_detector = cv.CascadeClassifier(
    './haarcascade/haarcascade_frontalface_default.xml')

def face_detect_demo(img):
    #将图片灰度
    gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
    faces = face_detector.detectMultiScale(gray)
    ans = []
    for x, y, w, h in faces:
        cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # 人脸识别
        id, confidence = recogizer.predict(gray[y:y + h, x:x + w])
        # print('标签id:', id, '置信评分：', confidence)
        print(confidence)
        ans.append(confidence)

    cv.namedWindow('result', 0)
    cv.resizeWindow('result', 600, 500)
    cv.imshow('result', img)

    if ans == []:
        return
    elif min(ans) < 60:
        print("符合标准")
        insert_sql()
        time.sleep(1)

#读取视频
# cap=cv.VideoCapture('video.mp4')
# cap=cv.VideoCapture('test.mp4')
cap= cv.VideoCapture(0)  # 0为电脑内置摄像头

while True:
    # cap = cv.VideoCapture(0)
    flag,frame=cap.read()
    # print('flag:',flag,'frame.shape:',frame.shape)
    if not flag:
        break
    # cv.imshow("video", frame)
    face_detect_demo(frame)
    if ord('q') == cv.waitKey(10):
        break

cv.destroyAllWindows()
cap.release()